#![allow(unused_variables)]

#[derive(Debug)]
struct File {
    name: String,
    data: Vec<u8>,
}
impl File {
    // 定义new函数
    fn new(name: &str) -> File {
        File {
            name: String::from(name),
            data: Vec::new(),
        }
    }
    // 预存入数据
    fn new_with_data(name: &str, data: &Vec<u8>) -> File {
        let mut f = File::new(name);
        f.data = data.clone();
        f
    }
    // 使用self替代f
    fn read(self: &File, save_to: &mut Vec<u8>) -> usize {
        let mut tmp = self.data.clone();
        let read_length = tmp.len();

        save_to.reserve(read_length); //分配内存
        save_to.append(&mut tmp);
        read_length
    }
}
fn open(f: &mut File) -> bool {
    true
}
fn close(f: &mut File) -> bool {
    true
}

fn read(f: &File, save_to: &mut Vec<u8>) -> usize {
    //不返回数据
    let mut tmp = f.data.clone();
    let read_length = tmp.len();

    save_to.reserve(read_length); //分配内存
    save_to.append(&mut tmp);
    read_length
}

fn main() {
    let f3_data = vec![114, 117, 115, 116, 33];

    let mut f3 = File::new_with_data("2.txt", &f3_data);
    let mut buffer: Vec<u8> = vec![];

    //与文件交互
    open(&mut f3);
    let f3_length = f3.read(&mut buffer);
    close(&mut f3);

    let text = String::from_utf8_lossy(&buffer); // 将Vec<u8>转为String,无效的字符会被换成乱码

    println!("{:?}", f3);
    println!("{} is {} bytes long", &f3.name, f3_length);
}
